#include<boost/asio.hpp>
#include<string>
#include <iostream>
using boost::asio::ip::tcp;
class service {
    public:
        //逐行读取客户的输入，发送的是字符串
        using value_type = std::string;
        //创建监听端口
        explicit service (
            boost::asio::io_service & service,
            unsigned short port = 42042):m_acceptor(service, tcp::endpoint(tcp::v4(), port))
            ,m_socket(service)
            {
            }
        //禁止复制，但可以移动
        service(const service & other) = delete;
        service( service && other) = default;
        //直到再message_service中注册并监听消息，才可以接收客户端的连接
        template<typename EmitFunction>
        void set_message_handler(EmitFunction emit) {
            m_emit = emit;
            do_accept();
        }
    
    private:
        //对客户端创建并启用session，读取一条消息，传递给m_emit。
        //make_shared_session方法创建一个指向session对象的共享指针
        void do_accept()
        {
            m_acceptor.async_accept(
                m_socket,
                [this](const boost::asio::error_code &error) {
                    if( !error) {
                        make_shared_session(
                            std::move(m_socket),m_emit
                        )->start();
                    } else {
                        std::cerr<<error.message() << std::endl;
                    }

                    do_accept();
                }
            );
        }
        tcp::acceptor m_acceptor;
        tcp::socket m_socket;
        std::function<void(std::string &&) > m_emit;
};